package com.sh3h.generator.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.sh3h.generator.web.domain.GenProject;
import com.sh3h.generator.web.dtos.GenProjectDto;
import com.sh3h.generator.web.dtos.Result;
import com.sh3h.generator.web.service.impl.GenProjectServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping({"/api/gen/projects"})
public class ProjectController {

    @Autowired
    private GenProjectServiceImpl datasourceService;

    @GetMapping("")
    public Result getByPage(int pageNum, int pageSize, String projectName, String projectCode) {
        Page<GenProject> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<GenProject> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(projectCode)) {
            queryWrapper.eq(GenProject::getProjectCode, projectCode);
        }
        if (!StringUtils.isNullOrEmpty(projectName)) {
            queryWrapper.like(GenProject::getProjectName, projectName);
        }
        Page<GenProject> datasourceList = datasourceService.page(page, queryWrapper);
        return Result.success(datasourceList);
    }

    @GetMapping("/all")
    public Result getAll() {
        List<GenProject> datasourceList = datasourceService.list();
        return Result.success(datasourceList);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") String id) {
        GenProject datasource = datasourceService.getById(id);
        return Result.success(datasource);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") String id) {
        Boolean result = datasourceService.removeById(id);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    public Result updateById(@RequestBody GenProjectDto dto) {
        GenProject datasource = GenProjectDto.ToModal(dto);
        Boolean result = datasourceService.updateById(datasource);
        return Result.success(result);
    }

    @PostMapping("")
    public Result insert(@RequestBody GenProjectDto dto) {
        GenProject datasource = GenProjectDto.ToModal(dto);
        Boolean result = datasourceService.save(datasource);
        return Result.success(result);
    }
}
